<template>
  <div class="menu-wrapper">
    <CategroyDialog ref="memberCategoryDialog" request="memberCategory" @confirm="dialogConfirm" />
    <office-dialog ref="officeDialog" @confirm="officeConfirm" />
    <el-form ref="MemberForm" :model="form" :rules="rules" label-width="120px">
      <div v-if="!memberType" style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">
        <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">基本信息</span>
      </div>
      <el-form-item label="客户名称" :prop="'member.name'" :rules="rules.name">
        <el-input v-model="form.member.name" placeholder="请输入客户名称" style="width: 200px" />
      </el-form-item>
      <div style="display: flex">
        <el-form-item label="注册手机" :prop="'member.mobile'" :rules="rules.mobile">
          <el-input v-model="form.member.mobile" type="Number" placeholder="请输入注册手机" style="width: 200px" />
        </el-form-item>
        <el-form-item label="会员编码" >
          <el-input v-model="form.member.code" onkeyup="this.value=this.value.replace(/[^\d.]/g,'');"  maxlength="6"  placeholder="请输入会员编码" style="width: 200px" />
        </el-form-item>
      </div>

      <div style="display: flex;">
        <el-form-item label="客户等级" :prop="'member.vip'" :rules="rules.vip">
          <el-select v-model="form.member.vip" style="width: 200px" placeholder="请选择类型" @change="change">
            <el-option v-for="item in vips" :label="item.name" :value="item.vip" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户分类">
          <el-input v-model="memberCategoryName" style="width: 200px" suffix-icon="el-icon-arrow-down" placeholder="请选择客户分类" @focus="dialogShow" />
        </el-form-item>
      </div>
      <el-form-item label="收货人" prop="consignee">
        <el-input v-model="form.consignee" style="width: 200px" placeholder="请输入收货人名称" />
      </el-form-item>
      <div style="display: flex">
        <el-form-item label="选择小区或楼宇" prop="building">
          <el-button v-show="!form.building" type="primary" round @click="mapShowFn"><i class="el-icon-map-location" /> 点击选择</el-button>
          <el-tooltip class="item" effect="dark" content="点击重新选择小区或楼宇" placement="top">
            <el-link v-show="form.building" type="primary" :underline="false" @click="mapShowFn">{{ form.building }}</el-link :underline="false">
          </el-tooltip>
        </el-form-item>
        <el-form-item label="默认地址" prop="isDefault" style="margin-left: 85px">
          <el-switch v-model="form.isDefault" active-color="#13ce66" inactive-color="#ff4949" />
        </el-form-item>
      </div>

      <div style="display: flex;">
        <el-form-item label="门牌号" prop="roomNumber">
          <el-input v-model="form.roomNumber" style="width: 200px" placeholder="请输入门牌号" />
        </el-form-item>
        <el-form-item label="楼层" prop="level">
          <el-select v-model="form.level" style="width: 200px" placeholder="请选择">
            <el-option v-for="item in levelOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </div>
      <div>
        <el-form-item label="所在地" prop="areaId" style="width: 640px">
            <Distpicker @selected="onSelected" :province="district.province" :city="district.city" :area="district.area" ></Distpicker>
        </el-form-item>
      </div>

      <div v-if="!memberType" style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">
        <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">详细信息</span>
      </div>
      <div style="display: flex;" v-if="!memberType">
        <el-form-item label="客户类型" prop="memberType">
          <el-select v-model="form.member.memberType" style="width: 200px" placeholder="请选择类型">
            <el-option label="个人" value="0" />
            <el-option label="法人企业" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item :label="optionsType" prop="paymentPluginId">
          <el-select v-model="form.member.paymentPluginId" style="width: 200px" placeholder="请选择付款方式">
            <el-option v-for="item in optionsForm" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>
      </div>
      <el-form-item label="联系电话" v-if="!memberType">
        <el-input v-model="form.member.phone" style="width: 520px" placeholder="可填写多个联系电话,用&quot;,&quot;分割" />
      </el-form-item>
      <div style="display: flex;" v-if="!memberType">
        <el-form-item label="所属企业">
          <el-select v-model="form.member.companyId" style="width: 200px" filterable :filter-method="productMethod" placeholder="请选择企业">
            <el-option v-for="item in companyList" :key="item.value" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="电子邮箱">
          <el-input v-model="form.member.email" style="width: 200px" placeholder="请填写电子邮箱" />
        </el-form-item>
      </div>
      <div style="display: flex;" v-if="!memberType">
        <el-form-item label="所属部门" prop="officeName">
          <el-input v-model="officeName" placeholder="请选择所属部门" style="width: 200px" suffix-icon="el-icon-arrow-down" @focus="officeShow" />
        </el-form-item>
        <el-form-item label="推荐人名" prop="officeName">
          <el-select
            v-model="memberName"
            style="width: 200px"
            :filter-method="remoteMethod"
            value-key="id"
            filterable
            placeholder="请选择"
            @change="selectMember"
            @focus="memberFocus"
          >
            <el-option v-for="item in memberList" :key="item.id" :label="item.name" :value="item" />

            <el-option key="-" style="background-color: #DCDFE6;text-align: center;" label="底部隐藏块" value="-" />
            <el-option key="/" style="background-color: #909399;color:white ;text-align: center;position: absolute;bottom:0;width: 100%" label="--- 搜索客户 ---" value="/" />
          </el-select>
        </el-form-item>
      </div>

      <el-form-item>
        <el-button type="primary" :loading="clicked" @click="saveMember('MemberForm')">完 成</el-button>
      </el-form-item>
    </el-form>

    <el-dialog title="位置信息" :visible.sync="mapShow" top="5vh" width="800px" append-to-body>
      <Map :initcenter="[form.lng, form.lat]" @getMap="getMap" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="mapShow = false">取 消</el-button>
        <el-button type="primary" @click="savelngLat">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      v-el-drag-dialog
      title="双击选择客户"
      :visible.sync="memberTableVisible"
      width="950px"
      append-to-body
      :before-close="memberTableClose"
    >
      <div style="position: relative">
        <member-table @memberDouble="memberDouble" @addMemberClick="addMemberClick" @memberTableClose="memberTableClose" />
      </div>
    </el-dialog>
  </div>
</template>
<style scoped>
  .menu-wrapper {
    margin: 15px;
  }
</style>
<script>
  import Distpicker from '@/components/Distpicker/Distpicker'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import { list as memberList } from '@/api/member'
import { list } from '../../api/vip'
import { list as companys } from '../../api/company'
import { EventBus } from '@/api/eventBus'
import OfficeDialog from '@/components/OfficeDialog'
import utils from '../../utils/utils.js'
import { save } from '@/api/member'
import CategroyDialog from '@/components/CategoryDialog'
import Map from '@/components/GaodeMap/index'
import MemberTable from '@/components/MemberTable/index'

export default {
  name: 'MemberAdd',
  filters: {},
  directives: { elDragDialog },
  components: { CategroyDialog, OfficeDialog, Map, MemberTable,Distpicker },
  props: [
    'memberType',
    'clickPhone'
  ],
  data() {
    return {
      isMemberName:'',
      memberName:'',
      memberList: [],
      officeName: '',
      callType:'',
      memberId: '',
      vips: [],
      clicked: false, // 按钮防双击
      mapShow: false,
      tempLng: '',
      tempLat: '',
      tempAddress: '',
      tempAreaId: '',
      tempAois: '',
      memberTableVisible: false,
      tempAreaName: '',
      form: {
        address: '',
        building: '',
        consignee: '',
        isDefault: true,
        lat: '',
        lng: '',
        level: 0,
        phone: '',
        roomNumber: '',
        member: {
          address: '',
          areaId: '',
          code:'',
          areaName: '',
          promoterId: '',
          companyId: '',
          officeId: '',
          mobile: '',
          gender:'0',
          email: '',
          paymentPluginId:'',
          vip: '',
          memberCategoryId: '',
          memberType: '0'
        }
      },
      district: { province: 440000, city: '广州市', area: '海珠区' },
      companyList: [],
      vipName: '',
      memberCategoryName: '',
      dateName: '出生日期',
      optionsType: '付款方式',
      levelOptions: [
        { label: '有电梯', value: 0 },
        { label: '一层楼', value: 1 },
        { label: '二层楼', value: 2 },
        { label: '三层楼', value: 3 },
        { label: '四层楼', value: 4 },
        { label: '五层楼', value: 5 },
        { label: '六层楼', value: 6 },
        { label: '七层楼', value: 7 },
        { label: '八层楼', value: 8 },
        { label: '九层及以上', value: 9 }
      ],
      optionsForm: [
        { name: '现金客户', value: 'cashPayPlugin' },
        { name: '月结客户', value: 'debtPayPlugin'},
      ],
      rules: {
        name: [
          { required: true, message: '请输入客户名称', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入注册手机', trigger: 'blur' }
        ],
        vip: [
          { required: true, message: '请选择客户等级', trigger: 'blur' }
        ],
        consignee: [
          { required: true, message: '请输入收货人名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        building: [
          { required: true, message: '选择小区或楼宇', trigger: 'blur' }
        ],
        roomNumber: [
          { required: true, message: '请输入门店号', trigger: 'blur' }
        ],
        level: [
          { required: true, message: '请选择楼层', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    if (this.$route.query.type!=undefined||this.$route.query.type!=''||this.$route.query.type!=null){
      this.callType=this.$route.query.type
    }
    if (this.clickPhone!=''||this.clickPhone!=undefined||this.clickPhone!=null){
        this.form.member.mobile=this.clickPhone
    }

    this.loadCompany('')
    this.loadMember('')
    this.loadVip()
  },
  methods: {
    mapShowFn() {
      this.mapShow = !this.mapShow
    },
    getMap(lng, lat, addressData) {
      // console.log(lng, lat, addressData)
      // 定义变量保存经纬度和地址
      this.tempLng = lng
      this.tempLat = lat
      this.tempAreaId = addressData.addressComponent.adcode
      this.tempAois = addressData.formattedAddress
      this.tempAreaName = `${addressData.addressComponent.province}${addressData.addressComponent.city}${addressData.addressComponent.district}`
    },
    memberFocus() {
      if (this.form.member.promoterId != null || this.form.member.promoterId != '') {
        this.isMemberName=this.memberName
        this.memberId = this.form.member.promoterId
      }

    },
    selectMember(data) {
      var _this = this
      if (data == '/') {
        _this.form.member.promoterId = ''
        _this.memberTableVisible = true
      } else {
        _this.memberName=data.name
        _this.form.member.promoterId = data.id
      }
    },
    addMemberClick(val) {
      val.forEach(item => {
        this.form.member.promoterId = item.id
        this.memberName=item.name
      })
    },
    memberDouble(data) {
      this.form.member.promoterId = data.id
      this.memberName=data.name
    },
    memberTableClose() {
      this.form.member.promoterId = this.memberId
      this.memberName=this.isMemberName
      this.memberTableVisible = false
    },
    savelngLat() {
      this.form.lng = this.tempLng
      this.form.lat = this.tempLat
      // this.form.address = this.tempAddress
      this.form.building = this.tempAois
      this.form.member.areaId = this.tempAreaId
      this.form.member.areaName = this.tempAreaName
      this.mapShowFn()
    },
    // 会员选择
    loadMember(query) {
      var _this = this
      const params = new URLSearchParams()
      params.append('name', query)
      memberList(params).then(response => {
        console.log(response)
        _this.memberList = response.data.data
      }).catch(error => {
        console.log(error)
      })
    },
    change(e) {
      console.log(e)
    },
    remoteMethod(query) {
      this.loadMember(query)
    },
    productMethod(query) {
      this.loadCompany(query)
    },
    officeConfirm(val) {
      this.form.member.officeId = val.id
      this.officeName = val.name
    },
    officeShow() {
      console.log('点击了')
      this.$refs.officeDialog.show()
    },
    loadVip() {
      list().then(res => {
        this.vips = res.data.data
      })
    },
    loadCompany(query) {
      companys({ name: query }).then(res => {
        this.companyList = res.data.data
      })
    },

    onSelected(val) {
      if (!utils.isNull(val.area) && !utils.isNull(val.area.code)) {
        this.form.areaId = val.area.code
        this.form.areaName = val.province.value+val.city.value+val.area.value
      }else if (!utils.isNull(val.city) && !utils.isNull(val.city.code)){
        this.form.areaId = val.city.code
        this.form.areaName = val.province.value+val.city.value

      }else if (!utils.isNull(val.province) && !utils.isNull(val.province.code)){
        this.form.areaId = val.province.code
        this.form.areaName = val.province.value
      }
    },
    dialogShow() {
      console.log('点击了')
      this.$refs.memberCategoryDialog.show()
    },
    dialogConfirm(val) {
      console.log(val)
      this.memberCategoryName = val.name
      this.form.member.memberCategoryId = val.id
    },
    saveMember(form) {
      this.$refs[form].validate((valid) => {
        if (valid) { // 校验表单
          this.clicked = true
          this.form.address = this.form.building + this.form.roomNumber
          const params = new URLSearchParams()
          params.append('address', this.form.address)
          params.append('building', this.form.building)
          params.append('consignee', this.form.consignee)
          params.append('isDefault', this.form.isDefault)
          params.append('lat', this.form.lat)
          params.append('lng', this.form.lng)
          params.append('level', this.form.level)
          if (utils.isNull(this.form.phone)) {
            params.append('phone', this.form.member.mobile)
          } else {
            params.append('phone', this.form.phone)
          }
          params.append('roomNumber', this.form.roomNumber)
          save(params, this.form.member).then(response => {
            this.clicked = false
            if (response.type == 'success') {
              if (!utils.isNull(this.memberType)) {
                this.$emit('memberClick', response.data)
              } else {
                if (utils.isNull(this.callType)){
                  EventBus.$emit('member-add', response.data)
                  this.$store.dispatch('tagsView/delView', this.$route).then(({ visitedViews }) => {
                    this.$router.push({
                      path: '/member/list'
                    })
                  })// 关闭当前tab回到列表
                }else{
                  this.$store.dispatch('tagsView/delView', this.$route).then(({ visitedViews }) => {
                    this.$router.push({
                      path: '/order/add?id='+ response.data.id+'&name='+response.data.name
                    })
                  })
                }

              }
            } else {
              this.$message({
                message: response.content,
                offset: 120,
                center: true
              })
            }
          }).catch(() => {
            this.clicked = false
          })
        } else {
          return false
        }
      })
    },
    memberTypeClick(val) {
      console.log(val)
      var _this = this
      if (val == 0) {
        _this.dateName = '出生日期'
        _this.optionsType = '性别'
        _this.optionsForm = [
          { name: '男', value: 0 },
          { name: '女', value: 1 },
          { name: '隐藏', value: 2 }
        ]
      } else {
        _this.dateName = '创建日期'
        _this.optionsType = '企业类型'
        _this.optionsForm = [
          { name: '企业', value: 1 },
          { name: '事业单位', value: 2 }
        ]
      }
    }
  }
}
</script>
